<?php

class EventGiftPasswordController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/main';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			/*array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('admin'),
			),*/
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','view'),
				'users'=>array('admin'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete','admin1'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'actions'=>array('index'),
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new EventGiftPassword;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['EventGiftPassword']))
		{
			$model->attributes=$_POST['EventGiftPassword'];
				$sql="select * from zy_event_gift_password where password='".$model->password."'";
			
			$rs = Yii::app()->db->createCommand($sql)->queryAll();
			if($rs[0][password] == $model->password && $rs[0]['state'] == 1 && $model->service_number == ''){
				//密码已经存在,可以领取
				$this->redirect(array('create','state'=>6,'pass'=>$model->password));
			}
			if(!empty($rs)){
				$getSystemTime = getdate();	//获取当前系统时间
				/*领奖状态:0,未分配,未领奖,未过期 ,1,已经分配给用户，未领奖，未过期,2,已经分配给用户，未领奖，已过期,3,已经分配给客
					户，已领奖4. 未分配,未领奖，已过期
				*/
				if(strtotime("-1 week") <strtotime($rs[0]['time']) ){
					//1,已经分配给用户，未领奖，未过期
					if($rs[0]['state'] == 1){//必须从,网站页面填写代码,使得state状态为1,发奖员才能发奖成功
						$model->state = 3;
					
					}elseif($rs[0]['state'] == 2){
						//2,已经分配给用户，未领奖，已过期
						$this->redirect(array('create','state'=>2));
						
					}elseif($rs[0]['state'] == 3){
						//3,已经分配给客户，已领奖
						$this->redirect(array('create','state'=>3));
					}
					
				}else{
					//4. 未分配,未领奖，已过期
					$expire_date=date('Y-m-d',strtotime("+7 day",strtotime($rs[0]['time'])));
					$this->redirect(array('create','state'=>4,'password_expire_date'=>$expire_date));
				}
			}else{
				$this->redirect(array('create','state'=>5,'pass'=>$model->password));
				//return '领奖密码不存在';
			}
			
			$upsql="update zy_event_gift_password set `service_number`='".$model->service_number."' ,`state` ='".$model->state."' where 

			password='".$model->password."'";
			$rss = Yii::app()->db->createCommand($upsql)->execute();
			//在做密码兑奖的时候,状态值必须为1
			if($rss){
				$upsqls="update zy_event set `Used_gift_number` = Used_gift_number + 1 where event_id='".$rs[0][event_id]."'";
				Yii::app()->db->createCommand($upsqls)->execute();
				$this->redirect(array('eventGiftPassword/admin'));//return '领奖成功';
			}
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['EventGiftPassword']))
		{
			$model->attributes=$_POST['EventGiftPassword'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->gift_password_id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('EventGiftPassword');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new EventGiftPassword('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['EventGiftPassword']))
			$model->attributes=$_GET['EventGiftPassword'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}
	
	public  function actionAdmin1()
	{		
		
		$model=new EventGiftPassword('search2');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['EventGiftPassword']))
			$model->attributes=$_GET['EventGiftPassword'];
						
		$this->render('admin1',array(
				'model'=>$model,
		));
		
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return EventGiftPassword the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=EventGiftPassword::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param EventGiftPassword $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='event-gift-password-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
